package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Xiao
 * @date 2021/10/24
 */
@DubboService
public class RecommentUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 思路分析：根据toUserId查询，根据score排序，获取第一条数据
     *
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //构建Criteria、Query对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        //调用MongoTemplate查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendUserList(Integer page, Integer pagesize, Long toUserId) {
        //构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        Query query = Query.query(criteria);
        //查询数据总记录数
        Long counts = mongoTemplate.count(query, RecommendUser.class);
        //查询数据列表
        Long skip = Long.valueOf((page - 1) * pagesize);
        query.with(Sort.by(Sort.Order.desc("score"))).limit(pagesize).skip(skip);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        //构造返回值
        return new PageResult(page, pagesize, Integer.parseInt(String.valueOf(counts)), recommendUsers);
    }

    @Override
    public RecommendUser getFateValue(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("toUserId").is(toUserId);
        RecommendUser recommendUser = mongoTemplate.findOne(Query.query(criteria), RecommendUser.class);
        if (ObjectUtil.isEmpty(recommendUser)) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(99D);
        }
        return recommendUser;
    }

    @Override
    public List<RecommendUser> getRecommends(Long userId, List<Long> likeUserIds, Integer count) {
        //构造查询推荐用户的条件
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);
        //使用统计函数，随机获取推荐的用户列表
        TypedAggregation<RecommendUser> aggregation = TypedAggregation.newAggregation(
                RecommendUser.class,
                Aggregation.match(criteria),
                Aggregation.sample(count));
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(aggregation, RecommendUser.class);
        return aggregate.getMappedResults();
    }

    @Override
    public Map<Long, RecommendUser> selectByIds(Long userId, List<Long> userIds) {
        Criteria criteria = Criteria
                .where("toUserId").is(userId)
                .and("userId").in(userIds);
        List<RecommendUser> recommendUsers = mongoTemplate.find(Query.query(criteria), RecommendUser.class);
        return recommendUsers.stream().collect(Collectors.toMap(RecommendUser::getUserId, Function.identity()));
    }

    @Override
    public List<RecommendUser> selectById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query, RecommendUser.class);
    }

    @Override
    public void removeSameRecommendUser(ArrayList<RecommendUser> users) {
        for (RecommendUser user : users) {
            mongoTemplate.remove(user);
        }
    }

    /**
     * 随机获取推荐数据
     * @param pagesize
     * @return
     */
    @Override
    public List<RecommendUser> getRandomRecommendUsers(Integer pagesize) {
        //创建统计对象，设置统计参数
        TypedAggregation<RecommendUser> aggregation = Aggregation.newAggregation(
                RecommendUser.class,
                Aggregation.sample(pagesize));
        //调用mongoTemplate.aggregate()方法进行统计
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(aggregation, RecommendUser.class);
        //获取统计结果
        return aggregate.getMappedResults();
    }
}
